from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from Book.models import Book
from WebSite.BaseView import BaseView


class IndexPage(BaseView):
    def get(self, request):
        return render(request, 'statistic.html')


class BookTypeStatistic(BaseView):
    def get(self, request):
        book_list = Book.objects.values('book_type_id').annotate(Count=Count('book_type_id')).order_by()
        result = book_list
        countResult = []
        if result is not None:
            for item in result:
                countResult.append(item)
        resultData = {
            "countResult": countResult
        }
        return JsonResponse(resultData, safe=False)

    # book = Book.objects.all()
    # if barcode != '':
    #     book = book.filter(barcode__contains=barcode)
    # if bookName != '':
    #     book = book.filter(bookName__contains=bookName)
    # if publishDate != '':
    #     book = book.filter(publishDate__contains=publishDate)
    # if bookTypeObj_bookTypeId != '0':
    #     book = book.filter(bookTypeObj=bookTypeObj_bookTypeId)

    @staticmethod
    def get_query_sql(bookName, bookType, bookPublishDate, page, pageSize):
        search_sql = "select book_id,book_name,book_price,book_type_id,book_count" \
                     ",book_publish,book_publish_date,book_introduction,book_image_path" \
                     ",create_time,update_time from t_book where 1=1 "
        if len(bookName) > 0:
            search_sql = search_sql + " and book_name='" + bookName + "'"
        if len(bookType) > 0:
            search_sql = search_sql + " and book_type_id='" + bookType + "'"
        if len(bookPublishDate) > 0:
            search_sql = search_sql + " and date_format(book_publish_date,'%Y-%m-%d')='" + bookPublishDate + "'"
        search_sql = search_sql + " limit " + str((page - 1) * pageSize) + "" + str(page * pageSize)
        return search_sql

    @staticmethod
    def get_query_count_sql(bookName, bookType, bookPublishDate):
        search_sql = "select count(*) from t_book where 1=1 "
        if len(bookName) > 0:
            search_sql = search_sql + " and book_name='" + bookName + "'"
        if len(bookType) > 0:
            search_sql = search_sql + " and book_type_id='" + bookType + "'"
        if len(bookPublishDate) > 0:
            search_sql = search_sql + " and date_format(book_publish_date,'%Y-%m-%d')='" + bookPublishDate + "'"
        return search_sql
